package com.maben.udp.test002;
 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 接收端
 */
public class ChatReceiver implements Runnable {
    String  yourHostName;
    int myPort;
    DatagramSocket socket;
 
    public ChatReceiver(String yourHostName, int myPort) {
        this.yourHostName = yourHostName;
        this.myPort = myPort;
        try {
            this.socket = new DatagramSocket(myPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        try {
            while(true){
                socket.receive(packet);
                String s = new String(packet.getData(),0,packet.getLength());
                System.out.println(yourHostName + ": " + s);
                if(s.equals("bye")) break;
            }
        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            socket.close();
        }

    }
}